<template>
  <div class="edit">
    <van-overlay :show="overlayShow" :z-index="1000">
      <div style="display: flex;align-items: center;justify-content: center;height: 100%;">
        <van-loading type="spinner" color="#1989fa">请稍候...</van-loading>
      </div>
    </van-overlay>
    <headcom v-if="JSON.stringify(jsondata.headinfo) !== '{}'" :jsondata="headdata"></headcom>
    <div>
      <div style="padding: 12px 12px 0px 5.07vw; display: flex; justify-content: space-between;">
        <div>
          <span style="font-weight: bold;">拜访动作：</span>
          <span style="color: #FF9100;">{{ title }}</span>
        </div>
        <div>
          <van-button plain type="info" size="mini">添加一行</van-button>
          <van-button plain type="info" size="mini" @click="savelog('skip')" v-if="canskip">跳过</van-button>
        </div>
      </div>
      <div style="padding: 7px; margin-bottom: 50px;">
        <template size="large" v-for="item in jsondata.head" :name="item.grouptitle" :title="item.grouptitle">
          <template style="border:0px;">
            <div :key="item.grouptitle" style="background-color: #F6F6F6; padding: 2.14vw 1.87vw 1vw 1.87vw;">
              <template v-for="(itemdata, index) in item.groupvalue">
                <div style="border-bottom:1px solid #ebedf0" v-if="fields.indexOf(itemdata.sField) >= 0" :key="itemdata.ID">
                  <idatetime ishead :itemdata="itemdata" v-if="itemdata.sUIType == 'datetime'" />
                  <icode ishead :itemdata="itemdata" v-else-if="itemdata.sUIType == 'code'" />
                  <ienum ishead :itemdata="itemdata" v-else-if="itemdata.sUIType == 'enum'" :jsondata="jsondata" :idobject="idobject" />
                  <iref ishead :itemdata="itemdata" v-else-if="itemdata.sUIType == 'ref'" :clickmodel.sync="clickmodel" :clickfrom.sync="clickfrom" :clickindex.sync="clickindex" :jsondata="jsondata" />
                  <ibool ishead :itemdata="itemdata" v-else-if="itemdata.sUIType == 'bool'" :jsondata="jsondata" :idobject="idobject" />
                  <ifile ishead :itemdata="itemdata" v-else-if="itemdata.sUIType == 'file'" :jsondata="jsondata" />
                  <ipicture ishead :itemdata="itemdata" v-else-if="itemdata.sUIType == 'picture'" :jsondata="jsondata" />
                  <istring ishead :itemdata="itemdata" v-else-if="itemdata.sUIType == 'string'" :jsondata="jsondata" :idobject="idobject" />
                  <!--<imap ishead :itemdata="itemdata" v-else-if="itemdata.sUIType == 'map'" :jsondata="jsondata" :item="item" />-->
                  <imap2 ishead :itemdata="itemdata" v-else-if="itemdata.sUIType == 'map'" :jsondata="jsondata" :item="item" />
                  <istring ishead :itemdata="itemdata" v-else :jsondata="jsondata" :idobject="idobject" />
                </div>
              </template>
            </div>
          </template>
        </template>
        <!--子表，可能有用，暂时不删-->
        <!--<div v-for="(itembody, indexName) in jsondata.body" :key="indexName" :name="indexName" :title="indexName">
        <van-collapse v-model="activeBodyNams">
          <van-collapse-item size="large" v-for="(item, index) in jsondata.bodydata[indexName]" :key="indexName + index" :name="indexName + index" :title="indexName + (index + 1)">
            <van-cell-group style="border:0px;">
              <div style="border-bottom:1px solid #ebedf0" v-for="itemdata in item" :key="itemdata.ID">
                <idatetime :index="index" :itemdata="itemdata" v-if="itemdata.sUIType == 'datetime'" />
                <icode :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'code'" />
                <ienum :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'enum'" :jsondata="jsondata" :idobject="idobject" />
                <iref :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'ref'" :clickmodel.sync="clickmodel" :clickfrom.sync="clickfrom" :clickindex.sync="clickindex" :jsondata="jsondata" :indexName="indexName" />
                <ibool :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'bool'" :jsondata="jsondata" :idobject="idobject" />
                <ifile :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'file'" :jsondata="jsondata" />
                <ipicture :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'picture'" :jsondata="jsondata" />
                <istring :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'string'" :jsondata="jsondata" :indexName="indexName" :idobject="idobject" />
                <imap :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'map'" :jsondata="jsondata" :item="item" />
                <istring :index="index" :itemdata="itemdata" v-else :jsondata="jsondata" :indexName="indexName" :idobject="idobject" />
              </div>
              <van-button type="danger" size="small" block style="font-size:14px; font-weight:bold;background-color: #fff;color:#ff4d4f; border-color: #fff" @click="delRow(indexName, index)">- 删除{{ indexName }}{{ index + 1 }}</van-button>
            </van-cell-group>
          </van-collapse-item>
        </van-collapse>
        <van-button v-show="jsondata.hasdetail === '1'" size="large" plain style="color:#039be5 ;border-color: #fff" @click="addRow(indexName)">+ 增加明细</van-button>
      </div>-->
        <div v-if="actionType == '签到'" style="text-align: center; margin-top: 10vw;">
          <button class='roundCir' @click="qiandao">签到<br><span style="font-size: 20px">{{ this.qiandaotime }}</span></button>
        </div>
        <div v-if="actionType == '签退'" style="text-align: center; margin-top: 10vw;">
          <button class='roundCir' @click="qiantui">签退<br><span style="font-size: 20px">{{ this.qiantuitime }}</span></button>
        </div>
      </div>
    </div>
    <van-tabbar v-if="actionType != '签到'" v-model="active" safe-area-inset-bottom>
      <van-tabbar-item @click="save">保存</van-tabbar-item>
      <!-- <van-tabbar-item @click="savelog('skip')" v-if="!ended">跳过</van-tabbar-item> -->
      <!-- <van-tabbar-item @click="savesubmit">保存并提交</van-tabbar-item> -->
    </van-tabbar>
  </div>
</template>

<script>
import Vue from 'vue'
import { Panel, Dialog, Search, List, Cell, PullRefresh, Toast, Tabbar, TabbarItem, Popup, DatetimePicker, ActionSheet, Tab, Tabs, Collapse, CollapseItem, Checkbox, CheckboxGroup, Uploader, Overlay, Loading, Rate, NumberKeyboard } from 'vant'
import qs from 'qs'
import useInput from '@/utils/useinput'
import * as dd from 'dingtalk-jsapi'
import headcom from '@/components/scenario/Head.vue'
import imap2 from '../../components/input/imap2.vue'
Vue.use(Panel).use(Dialog).use(useInput).use(Search).use(List).use(Cell).use(PullRefresh).use(Toast).use(Tabbar).use(TabbarItem).use(Popup).use(DatetimePicker).use(ActionSheet).use(Tab).use(Tabs).use(Collapse).use(CollapseItem).use(Checkbox).use(CheckboxGroup).use(Uploader).use(Overlay).use(Loading).use(Rate).use(NumberKeyboard)
export default {
  name: 'edit',
  components: { headcom, imap2 },
  data () {
    return {
      title: this.$route.query.stitle,
      idobject: this.$route.query.idobject,
      actiontype: this.$route.query.atype,
      headobject: this.$route.query.headobject,
      headid: this.$route.query.headid,
      fields: this.$route.query.fields,
      scenario: JSON.parse(this.$route.query.scenario),
      lastActionIndex: this.$route.query.lastActionIndex,
      ended: this.$route.query.ended,
      actionType: this.$route.query.actionType,
      canskip: this.$route.query.canskip,
      jsondata: {},
      headdata: {},
      index: 0,
      active: 0,
      activeNames: [''],
      activeBodyNams: [''],
      clickmodel: {},
      isLoad: false,
      clickfrom: '',
      clickindex: 0,
      isDisable: false,
      overlayShow: false,
      qiandaotime: '',
      qiantuitime: ''
    }
  },
  created () {
    //console.log('created......', this.actionType, this.$route.query)
    // this.fetchData()
    let _this = this
    document.title = this.title
    //console.log('document.title', document.title)
    if (dd.env.platform !== 'notInDingTalk') {
      dd.ready(function () {
        dd.biz.navigation.setTitle({
          title: _this.$route.query.stitle
        })
      })
    }
  },
  mounted: function () {
    //console.log('action ...')
    //console.log('start action')
    //console.log('fields', this.fields, this.ended)
    this.qiandaotime = this.currenttime().split(' ')[1].substring(0, 5)
    this.qiantuitime = this.currenttime().split(' ')[1].substring(0, 5)
    if (!this.isLoad) {
      this.axios({
        method: 'post',
        url: '/api/' + this.headobject + '.check.do',
        data: qs.stringify({ [this.headobject + '_id']: this.headid })
      }).then(res => {
        this.headdata = res.data.jsondata
        //console.log('headdata', this.headdata)
      }).catch(res => {
        this.reserror(res)
      })

      let data = {
        sobject: this.idobject,
        [this.idobject + '_id']: this.$route.query.itemid
      }
      this.axios({
        method: 'post',
        // url: '/api/' + this.idobject + '.' + this.actiontype + '.do',
        url: '/api/scenario.getaction.do',
        data: qs.stringify(data)
      }).then(res => {
        //console.log(res)
        if (res.data.flag === '1') {
          Toast(res.data.des)
          if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
            this.loginout()
          }
        } else {
          this.jsondata = res.data.jsondata
          for (let i = 0; i < res.data.jsondata.head.length; i++) {
            let itemgroup = this.jsondata.head[i].groupvalue
            for (let itemindex in itemgroup) {
              let itemdata = itemgroup[itemindex]
              if (itemdata.sUIType === 'datetime' && itemdata.sUITypeExp !== 'long') {
                itemdata.value = itemdata.value.substring(0, 10)
              }
            }
            this.activeNames.push(res.data.jsondata.head[i].grouptitle)
          }
          //console.log(this.jsondata)
          this.isLoad = true
        }
      }).catch(res => {
        this.reserror(res)
      })
    }
  },
  methods: {
    save () {
      //console.log('savelog', this.scenario)
      if (!this.isDisable) {
        this.overlayShow = true
        this.isDisable = true
        let data = {}
        data[this.idobject + '_id'] = this.$route.query.itemid
        for (let groupindex in this.jsondata.head) {
          let itemgroup = this.jsondata.head[groupindex].groupvalue
          for (let itemindex in itemgroup) {
            let itemdata = itemgroup[itemindex]
            if (itemdata.sUIType === 'ref') {
              data[itemdata.idObject + '_' + itemdata.sField] = itemdata.valuehidden
              data[itemdata.idObject + '_' + itemdata.sField + '_ref'] = itemdata.value
            } else if (itemdata.sUIType === 'enum') {
              data[itemdata.idObject + '_' + itemdata.sField] = itemdata.valuehidden
              data[itemdata.idObject + '_' + itemdata.sField + '_enum'] = itemdata.value
            } else if (itemdata.sUIType === 'file' || itemdata.sUIType === 'picture') {
              data[itemdata.idObject + '_' + itemdata.sField] = itemdata.valuehidden
              data[itemdata.idObject + '_' + itemdata.sField + '_title'] = itemdata.value
            } else {
              data[itemdata.idObject + '_' + itemdata.sField] = itemdata.value
            }
          }
        }
        for (let indexName in this.jsondata.bodydata) {
          for (let i = 0; i < this.jsondata.bodydata[indexName].length; i++) {
            let item = this.jsondata.bodydata[indexName][i]
            for (let itemindex in item) {
              let itemdata = item[itemindex]
              if (itemdata.sUIType === 'ref') {
                data[i + '_' + itemdata.idObject + '_' + itemdata.sField] = itemdata.valuehidden
                data[i + '_' + itemdata.idObject + '_' + itemdata.sField + '_ref'] = itemdata.value
              } else if (itemdata.sUIType === 'enum') {
                data[i + '_' + itemdata.idObject + '_' + itemdata.sField] = itemdata.valuehidden
                data[i + '_' + itemdata.idObject + '_' + itemdata.sField + '_enum'] = itemdata.value
              } else {
                data[i + '_' + itemdata.idObject + '_' + itemdata.sField] = itemdata.value
              }
            }
          }
        }
        this.axios({
          method: 'post',
          url: '/api/' + this.idobject + '.' + this.actiontype + 'save.do',
          data: qs.stringify(data)
        }).then(res => {
          this.isDisable = false
          this.overlayShow = false
          if (res.data.flag === '0') {
            Toast('保存成功')
            this.savelog('end')
          } else {
            Toast(res.data.des)
            if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
              this.loginout()
            }
          }
          //console.log(res)
        }).catch(res => {
          this.isDisable = false
          this.overlayShow = false
          //console.log(res)
        })
      }
    },
    qiandao () {
      for (let groupindex in this.jsondata.head) {
        let itemgroup = this.jsondata.head[groupindex].groupvalue
        for (let itemindex in itemgroup) {
          let itemdata = itemgroup[itemindex]
          if (itemdata.sField === 'dbegin') {
            itemdata.value = this.currenttime()
          }
        }
      }
      this.save()
    },
    qiantui () {
      for (let groupindex in this.jsondata.head) {
        let itemgroup = this.jsondata.head[groupindex].groupvalue
        for (let itemindex in itemgroup) {
          let itemdata = itemgroup[itemindex]
          if (itemdata.sField === 'dend') {
            itemdata.value = this.currenttime()
          }
        }
      }
      this.save()
    },
    savelog (states) {
      let data = {
        idscenario: this.$route.query.scenarioId,
        idaction: this.$route.query.actionId,
        sobject: this.headobject,
        iddata: this.$route.query.itemid,
        toobject: this.idobject,
        states: states
      }
      //console.log('savelog', data, this.$route.query.scenario)
      this.axios({
        method: 'post',
        url: '/api/scenario.savelog.do',
        data: qs.stringify(data)
      }).then(res => {
        if (res.data.flag === '0') {
          if (this.scenario.scenarioInfo.length && this.scenario.scenarioInfo.length > this.lastActionIndex && !this.ended) {
            let lastAction = this.scenario.scenarioInfo[this.lastActionIndex + 1]
            this.$router.push({
              name: 'action',
              query: {
                scenarioId: this.scenario.scenarioId,
                actionId: lastAction.actionId,
                itemid: lastAction.toId,
                headobject: this.headobject,
                headid: this.headid,
                idobject: lastAction.toBo,
                atype: lastAction.toPage,
                stitle: lastAction.actionName,
                fields: lastAction.fields,
                scenario: JSON.stringify(this.scenario),
                lastActionIndex: this.lastActionIndex + 1,
                actionType: lastAction.actionType
              }
            })
          } else {
            this.$router.push({ name: 'card', query: { idobject: this.headobject, itemid: this.headid } })
          }
        } else {
          Toast(res.data.des)
          if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
            this.loginout()
          }
        }
      }).catch(res => {
        this.isDisable = false
        this.overlayShow = false
        //console.log(res)
      })
    },
    currenttime () {
      let d = new Date()
      let year = d.getFullYear()
      let month = this.change(d.getMonth() + 1)
      let day = this.change(d.getDate())
      let hour = this.change(d.getHours())
      let minute = this.change(d.getMinutes())
      let second = this.change(d.getSeconds())
      let time = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
      return time
    },
    change (t) {
      if (t < 10) {
        return '0' + t
      } else {
        return t
      }
    },
    addRow (indexName) {
      let bodycopy = JSON.parse(JSON.stringify(this.jsondata.body[indexName]))
      this.jsondata.bodydata[indexName].push(bodycopy)
    },
    delRow (indexName, index) {
      if (this.jsondata.bodydata[indexName].length === 1) {
        Toast('至少保留一条表体行，不能删除！')
        return
      }
      Dialog.confirm({
        title: '',
        message: '你确定要删除' + indexName + ' ' + (index + 1) + '吗?'
      })
        .then(() => {
          // on confirm
          this.jsondata.bodydata[indexName].splice(index, 1)
        })
        .catch(() => {
          // on cancel
        })
    }
  },
  activated () {
    //console.log(this.$store.state.ref_show)
    //console.log(this.$store.state.ref_id)
    if (this.$store.state.ref_show !== '') {
      this.clickmodel.value = this.$store.state.ref_show
      this.clickmodel.valuehidden = this.$store.state.ref_id
      let fieldmap = this.clickmodel.fieldmap
      if (fieldmap !== undefined && fieldmap.length > 0) {
        let arrFieldmap = fieldmap.split(';')
        let item = this.$store.state.ref_item
        if (this.clickfrom === 'headdata') {
          for (let groupindex = 0; groupindex < this.jsondata.head.length; groupindex++) {
            let itemgroup = this.jsondata.head[groupindex]
            for (let itemindex = 0; itemindex < itemgroup.groupvalue.length; itemindex++) {
              let itemdata = itemgroup.groupvalue[itemindex]
              for (let fieldmapindex in arrFieldmap) {
                let arrFieldMapKey = arrFieldmap[fieldmapindex].split(':')
                if (this.$store.state.ref_field === arrFieldMapKey[1]) {
                  continue
                }
                if (arrFieldMapKey.length === 3 && arrFieldMapKey[2] !== '' && this.$store.state.ref_field !== arrFieldMapKey[2]) {
                  continue
                }
                if (itemdata.sField === arrFieldMapKey[1]) {
                  if (itemdata.sUIType === 'ref') {
                    itemdata.value = item[arrFieldMapKey[0] + '_ref']
                    itemdata.valuehidden = item[arrFieldMapKey[0]]
                  } else if (itemdata.sUIType === 'enum') {
                    itemdata.value = item[arrFieldMapKey[0] + '_enum']
                    itemdata.valuehidden = item[arrFieldMapKey[0]]
                  } else {
                    itemdata.value = item[arrFieldMapKey[0]]
                  }
                }
              }
            }
          }
        } else if (this.clickfrom === 'bodydata') {
          for (let itemindex in this.jsondata.bodydata[this.clickindex]) {
            let itemdata = this.jsondata.bodydata[this.clickindex][itemindex]
            for (let fieldmapindex in arrFieldmap) {
              let arrFieldMapKey = arrFieldmap[fieldmapindex].split(':')
              if (this.$store.state.ref_field === arrFieldMapKey[1]) {
                continue
              }
              if (arrFieldMapKey.length === 3 && arrFieldMapKey[2] !== '' && this.$store.state.ref_field !== arrFieldMapKey[2]) {
                continue
              }
              if (itemdata.sField === arrFieldMapKey[1]) {
                if (itemdata.sUIType === 'ref') {
                  itemdata.value = item[arrFieldMapKey[0] + '_ref']
                  itemdata.valuehidden = item[arrFieldMapKey[0]]
                } else if (itemdata.sUIType === 'enum') {
                  itemdata.value = item[arrFieldMapKey[0] + '_enum']
                  itemdata.valuehidden = item[arrFieldMapKey[0]]
                } else {
                  itemdata.value = item[arrFieldMapKey[0]]
                }
              }
            }
          }
        }
      }
      this.clickmodel = {}
      this.clickindex = 0
      this.clickfrom = ''
      this.$store.commit('clearRef')
    }
  }
}
</script>

<style scoped>
.fieldgroup_title {
  text-align: left;
  margin: 0px;
  padding: 25px 15px 15px;
  color: rgba(69, 90, 100, 0.6);
  font-weight: normal;
  font-size: 14px;
}

.roundCir {
  min-width: 150px;
  max-width: 150px;
  max-height: 150px;
  min-height: 150px;
  border-radius: 80px;
  font-size: 15px;
  color: white;
  background: #1989fa;
  border: 1px solid white;
  /*margin-left: 32vw;*/
}
</style>
